from flask import Flask
from flask import request
from werkzeug.utils import secure_filename
from model.deeplabv3p_xception65_humanseg import get_head_photo
from model.ultra_detector import detect_face_num
from utils.base64Utils import img2base64
from utils.resize_utils import resizeimg
import os
from gevent import pywsgi

app = Flask(__name__)


@app.route("/")
def hello_world():
    return "<p>Hello, World!</p>"


@app.route('/aiService/upload', methods=['POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files['file']
        file_name = secure_filename(file.filename)
        photo_path = f'uploads/{file_name}'
        file.save(photo_path)
        if detect_face_num(photo_path):
            gene_img_path = get_head_photo(photo_path, file_name)
            img200X200 = resizeimg(gene_img_path, 200, 200, './resized')
            img300X400 = resizeimg(gene_img_path, 300, 400, './resized')
            os.remove(gene_img_path)
            # base64img = "data:image/jpg;base64," + base64img
            originimgbase64 = "data:image/jpg;base64," + img2base64(photo_path)
            os.remove(photo_path)
            img200X200base64 = "data:image/jpg;base64," + img2base64(img200X200)
            img300X400base64 = "data:image/jpg;base64," + img2base64(img300X400)
            os.remove(img200X200)
            os.remove(img300X400)
            return {"code": 200, 'originimgbase64': originimgbase64, 'img200X200base64': img200X200base64, 'img300X400base64': img300X400base64}
        else:
            return {"code": 500, 'message': "上传图片不符合要求！"}


if __name__ == '__main__':
    server = pywsgi.WSGIServer(('0.0.0.0', 5000), app)
    server.serve_forever()
